<?php
// +----------------------------------------------------------------------
// | Azthink通用开发平台 [ TOMORROW IS ANOTHER DAY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 http://www.azthink.top All rights reserved.
// +----------------------------------------------------------------------
// | Author 李忠<azthink@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\File as FileModel;
use think\Controller;
use think\Exception;

/**
 * 文件控制器
 *
 * @author 李忠<azthink@qq.com>
 * @createAt 2018-09-12 16:08:42
 *
 */
class File extends Controller {
    public function upload() {
        if ($this->request->isPost()) {
            $file = request()->file('file');
            try {
                $data = FileModel::upload($file, config('attachment_upload'));
                return json(array('result' => 'ok', 'id' => $data['id']));
            } catch (Exception $e) {
                return json(array('result' => 'failed', 'message' => $e->getMessage()));
            }
        }
    }

    public function download($id) {
        $file = FileModel::get($id);
        return download($file['savepath'] . $file['savename'], $file['name']);
    }

    public function editor() {

        if ($this->request->isPost()) {
            $files = $this->request->file();
            if ($files) {
                try {
                    $data = FileModel::upload(array_shift($files), config('editor_upload'));
                    $data['url'] = input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME') . substr($data['savepath'], 1) . $data['savename'];
                    return json(array('error' => 0, 'url' => $data['url']));
                } catch (Exception $e) {
                    return json(array('error' => 1, 'message' => $e->getMessage()));
                }
            } else {
                return json(array('error' => 1, 'message' => '请选择上传文件'));
            }

        }
    }
}